<template>
  <div class="category-list-container">
    <div class="search-form">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" class="search-form-content">
        <div class="left-items">
          <el-form-item label="类目名称" prop="name">
            <el-input v-model="searchForm.name" placeholder="请输入类目名称"></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
              <el-option label="电子数码" :value="1"></el-option>
              <el-option label="珠宝首饰" :value="2"></el-option>
              <el-option label="古董" :value="3"></el-option>
              <el-option label="字画" :value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" :value="1"></el-option>
              <el-option label="禁用" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </div>
        <div class="right-items">
          <el-form-item>
            <el-button type="primary" @click="openAdd">添加类目</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <el-table :data="tableData" border style="width: 100%" v-loading="loading">
      <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
      <el-table-column prop="name" label="类目名称" min-width="150"></el-table-column>
      <el-table-column prop="type" label="类型" width="120">
        <template #default="scope">
          {{ getTypeText(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160"></el-table-column>
      <el-table-column prop="updateTime" label="更新时间" width="160"></el-table-column>
      <el-table-column label="操作" width="220" align="center">
        <template #default="scope">
          <el-button type="text" @click="openEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          <el-button type="text" @click="toggleStatus(scope.row)">
            {{ scope.row.status === 1 ? '禁用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="searchForm.page" :page-sizes="[10, 20, 50, 100]" :page-size="searchForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>

    <!-- 添加/编辑类目对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form :model="form" :rules="categoryRules" ref="formRef" label-width="80px">
        <el-form-item label="类目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入类目名称"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%">
            <el-option label="电子数码" :value="1"></el-option>
            <el-option label="珠宝首饰" :value="2"></el-option>
            <el-option label="古董" :value="3"></el-option>
            <el-option label="字画" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { getCategoryList, addCategory, updateCategory, deleteCategory, setCategoryStatus } from '@/api/category'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: '',
  page: 1,
  pageSize: 10
})

const searchFormRef = ref(null)
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('添加类目')
const form = reactive({ id: null, name: '', type: '', status: 1 })
const formRef = ref(null)

// 表单验证规则
const categoryRules = {
  name: [
    { required: true, message: '请输入类目名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ]
}

// 获取类型文本
const getTypeText = (type) => {
  const typeMap = {
    1: '电子数码',
    2: '珠宝首饰',
    3: '古董',
    4: '字画'
  }
  return typeMap[type] || '未知'
}

// 加载类目列表
const loadCategoryList = async () => {
  loading.value = true
  try {
    const res = await getCategoryList(searchForm)
    console.log('类目列表：', res)

    if (res && res.records) {
      tableData.value = res.records
      total.value = res.total
    } else if (res && res.data && res.data.records) {
      // 处理嵌套的data.records结构
      tableData.value = res.data.records
      total.value = res.data.total
    } else if (res && Array.isArray(res)) {
      // 直接是数组的情况
      tableData.value = res
      total.value = res.length
    } else if (res && res.data && Array.isArray(res.data)) {
      // data是数组的情况
      tableData.value = res.data
      total.value = res.data.length
    } else {
      // 未匹配到有效数据结构
      tableData.value = []
      total.value = 0
      console.error('未找到有效的数据结构:', res)
    }
  } catch (error) {
    console.error('加载类目列表失败:', error)
    ElMessage.error('加载类目列表失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  searchForm.page = 1
  loadCategoryList()
}

// 重置搜索
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  searchForm.page = 1
  loadCategoryList()
}

// 添加类目
const openAdd = () => {
  dialogTitle.value = '添加类目'
  Object.assign(form, { id: null, name: '', type: '', status: 1 })
  dialogVisible.value = true
}

// 编辑类目
const openEdit = (row) => {
  dialogTitle.value = '编辑类目'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      if (form.id) {
        // 编辑
        console.log('正在更新类目:', form)
        const res = await updateCategory(form)
        console.log('更新类目响应:', res)
        ElMessage.success('更新类目成功')
      } else {
        // 添加
        console.log('正在添加类目:', form)
        const res = await addCategory(form)
        console.log('添加类目响应:', res)
        ElMessage.success('添加类目成功')
      }

      dialogVisible.value = false
      loadCategoryList() // 重新加载列表
    } catch (error) {
      console.error(form.id ? '更新类目失败:' : '添加类目失败:', error)
      ElMessage.error(form.id ? '更新类目失败' : '添加类目失败')
    }
  })
}

// 删除类目
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该类目吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      console.log('正在删除类目:', row.id)
      const res = await deleteCategory(row.id)
      console.log('删除类目响应:', res)
      ElMessage.success('删除类目成功')
      loadCategoryList() // 重新加载列表
    } catch (error) {
      console.error('删除类目失败:', error)
      ElMessage.error('删除类目失败')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 修改类目状态
const toggleStatus = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'

  try {
    console.log(`正在${statusText}类目，ID: ${row.id}, 当前状态: ${row.status}, 新状态: ${newStatus}`)
    const res = await setCategoryStatus(newStatus, row.id)
    console.log(`${statusText}类目成功:`, res)

    // 更新本地状态
    row.status = newStatus
    ElMessage.success(`类目已${statusText}`)
  } catch (error) {
    console.error(`${statusText}类目失败:`, error)
    ElMessage.error(`${statusText}类目失败`)
  }
}

// 分页处理
const handleSizeChange = (val) => {
  searchForm.pageSize = val
  loadCategoryList()
}

const handleCurrentChange = (val) => {
  searchForm.page = val
  loadCategoryList()
}

// 页面加载时获取数据
onMounted(() => {
  loadCategoryList()
})
</script>

<style scoped>
.category-list-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-items {
  flex: 1;
}

.right-items {
  margin-left: auto;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>